//
//  AppDelegate.m
//  LvBao
//
//  Created by 范琦 on 16/6/1.
//  Copyright © 2016年 范琦. All rights reserved.
//

#import "AppDelegate.h"
#import "InformationViewController.h"
#import "BaseNavigationController.h"
#import "MineViewController.h"
#import "RDVTabBar.h"
#import "MainViewController.h"
#import "RDVTabBarController.h"
#import "RDVTabBarItem.h"
#import "IQKeyboardManager.h"
#import "YTKNetworkConfig.h"
#import "UserMangerDefaults.h"


#import "LogInViewController.h"

@interface AppDelegate ()<RDVTabBarControllerDelegate>
{
    NSString *version;
}
@property (nonatomic, strong) RDVTabBarController *rdvTabbarVC;
@property (nonatomic, strong) UIAlertView *aler;
@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.

    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault animated:NO];
    // token错误的通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(tokenError) name:@"tokenError" object:nil];
    
    [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"is_pop"];
    if (![[NSUserDefaults standardUserDefaults] objectForKey:@"version"]) {
        version = @"0";
    }else{
        version = [[NSUserDefaults standardUserDefaults] objectForKey:@"version"];
    }
    
    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    [center addObserver:self selector:@selector(logoutView) name:@"NSNotificationCenter_LOGOUT" object:nil];
    [center addObserver:self selector:@selector(setupControlls) name:@"NSNotificationCenter_LOGIN" object:nil];
    // 网络连接错误的通知
    [center addObserver:self selector:@selector(netError:) name:@"netError" object:nil];
    
    
    if ([UserMangerDefaults is_Login]) {
//        NSString *str = [[NSUserDefaults standardUserDefaults] objectForKey:@"imToken"];
        
//        [[RCIM sharedRCIM] connectWithToken:str success:^(NSString *userId) {
//            NSLog(@"与服务器建立连接成功");
//            [[RCIM sharedRCIM] setUserInfoDataSource:self];
//            
//        } error:^(RCConnectErrorCode status) {
//            NSLog(@"错误");
//            
//        } tokenIncorrect:^{
//            
//        }];
        
        [self setupControlls];
        
        
    } else {
        [self creatLoginController];
    }

    [self setKeyboard];
    
    // 设置baseUrl
    YTKNetworkConfig *config = [YTKNetworkConfig sharedInstance];
    config.baseUrl = @"http://lvbao.dev.hsydev.com/api.php";
    
    return YES;
}
#pragma mark -- ViewControllers 设置VC

// 由于token被踢下线
- (void)tokenError
{
    if (_aler == nil) {
        
        self.aler = [[UIAlertView alloc]initWithTitle:@"提示" message:@"您的账号已经异地登录" delegate:self cancelButtonTitle:nil otherButtonTitles:nil];
        [_aler show];
        [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(dismissAler) userInfo:nil repeats:NO];
    }
    
    [NSUSERDEFAULTS setBool:NO forKey:@"is_logIn"];
    [NSUSERDEFAULTS synchronize];
    
    LogInViewController *LogInVC = [[LogInViewController alloc] init];
    BaseNavigationController *rootViewController = [[BaseNavigationController alloc] initWithRootViewController:LogInVC];
    self.window.rootViewController = rootViewController;
}
// 网络连接错误的通知方法
- (void)netError:(NSNotification *)noti
{
    
    if (_aler == nil) {
        
        self.aler = [[UIAlertView alloc]initWithTitle:@"提示" message:noti.userInfo[@"msg"] delegate:self cancelButtonTitle:nil otherButtonTitles:nil];
        [_aler show];
        [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(dismissAler) userInfo:nil repeats:NO];
    }
    
    
}


- (void)dismissAler
{
    [_aler dismissWithClickedButtonIndex:0 animated:YES];
    _aler = nil;
}

- (void)logoutView
{
    LogInViewController *LogInVC = [[LogInViewController alloc] init];
    BaseNavigationController *rootViewController = [[BaseNavigationController alloc] initWithRootViewController:LogInVC];
    self.window.rootViewController = rootViewController;
}

- (void)setupControlls
{
    MainViewController *mainVC = [[MainViewController alloc] init];
    BaseNavigationController *naVC = [[BaseNavigationController alloc] initWithRootViewController:mainVC];
    
    InformationViewController *infromationVC = [[InformationViewController alloc] init];
    BaseNavigationController *naVC1 = [[BaseNavigationController alloc] initWithRootViewController:infromationVC];


    
    MineViewController *mineVC = [[MineViewController alloc] init];
    BaseNavigationController *naVC5 = [[BaseNavigationController alloc] initWithRootViewController:mineVC];
    
    _rdvTabbarVC = [[RDVTabBarController alloc] init];
    [_rdvTabbarVC setViewControllers:@[naVC, naVC1, naVC5]];
    _rdvTabbarVC.delegate = self;
    [self customizeTabBarForController:_rdvTabbarVC];
    self.window.rootViewController = _rdvTabbarVC;
//    [self ob];
    
}
//- (void)ob
//{
//    // 创建observer
//    CFRunLoopObserverRef observer = CFRunLoopObserverCreateWithHandler(CFAllocatorGetDefault(), kCFRunLoopAllActivities, YES, 0, ^(CFRunLoopObserverRef observer, CFRunLoopActivity activity) {
//        NSLog(@"----监听到RunLoop状态发生改变---%zd", activity);
//    });
//    
//    // 添加观察者：监听RunLoop的状态
//    CFRunLoopAddObserver(CFRunLoopGetCurrent(), observer, kCFRunLoopDefaultMode);
//    
//    // 释放Observer
//    CFRelease(observer);
//}

- (void)creatLoginController
{
    LogInViewController *LogInVC = [[LogInViewController alloc] init];
    BaseNavigationController *rootViewController = [[BaseNavigationController alloc] initWithRootViewController:LogInVC];
    self.window.rootViewController = rootViewController;
}

#pragma mark SETICON  设置图标
- (void)customizeTabBarForController:(RDVTabBarController *)tabBarController {
    
    
    UIImage *finishedImage = [UIImage imageNamed:@"background_nor"];
    
    UIImage *unfinishedImage = [UIImage imageNamed:@"background_nor"];
    NSArray *tabBarItemImages = @[@"首页空", @"消息空", @"我的空",];
    NSArray *selBarItemImages = @[@"首页", @"消息", @"我的",];
    NSArray *titleArr = @[@"首页", @"消息", @"我的"];
    NSInteger index = 0;
    
    for (RDVTabBarItem *item in [[tabBarController tabBar] items]) {
        [item setBackgroundSelectedImage:finishedImage withUnselectedImage:unfinishedImage];
        UIImage *selectedimage = [UIImage imageNamed:[selBarItemImages objectAtIndex:index]];
        UIImage *unselectedimage = [UIImage imageNamed:[tabBarItemImages objectAtIndex:index]];
        
        item.title = titleArr[index];
        
        [item setFinishedSelectedImage:selectedimage withFinishedUnselectedImage:unselectedimage];
        item.titlePositionAdjustment = UIOffsetMake(0, 3);
        item.imagePositionAdjustment = UIOffsetMake(0, 1);
        item.unselectedTitleAttributes = @{
                                           NSFontAttributeName: [UIFont systemFontOfSize:12],
                                           NSForegroundColorAttributeName: [UIColor colorWithHexString:@"666666"],
                                           };
        item.selectedTitleAttributes = @{
                                         NSFontAttributeName: [UIFont systemFontOfSize:12],
                                         NSForegroundColorAttributeName: [UIColor colorWithHexString:@"ff5000"],
                                         };
//        if (index == 2) {
//            item.imagePositionAdjustment = UIOffsetMake(0, -2);
//        }
        index++;
    }
    NSLog(@"%lu", (long)index);
}

-(void)setKeyboard
{
    IQKeyboardManager *manager = [IQKeyboardManager sharedManager];
    manager.enable = YES;
    manager.shouldResignOnTouchOutside = YES;
    manager.shouldToolbarUsesTextFieldTintColor = YES;
    manager.enableAutoToolbar = NO;
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

@end
